package com.yjb.tenet.boot.system.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjb.tenet.boot.system.application.mapper.SysDeptRelationMapper;
import com.yjb.tenet.boot.system.application.service.SysDeptRelationService;
import com.yjb.tenet.boot.system.domain.entity.SysDept;
import com.yjb.tenet.boot.system.domain.entity.SysDeptRelation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yin.jinbiao
 * @since 2022-05-30
 */
@Service
public class SysDeptRelationServiceImpl extends ServiceImpl<SysDeptRelationMapper, SysDeptRelation> implements SysDeptRelationService {

	@Resource
	private SysDeptRelationMapper sysDeptRelationMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveDeptRelation(SysDept sysDept) {
		List<SysDeptRelation> relationList = this.lambdaQuery().eq(SysDeptRelation::getDescendant, sysDept.getParentId()).list()
				.stream().map(sysDeptRelation -> {
					sysDeptRelation.setDescendant(sysDept.getDeptId());
					return sysDeptRelation;
				}).collect(Collectors.toList());
		if (CollUtil.isNotEmpty(relationList)) {
			this.saveBatch(relationList);
		}
		// 自己也要维护到关系表中
		SysDeptRelation own = new SysDeptRelation();
		own.setDescendant(sysDept.getDeptId());
		own.setAncestor(sysDept.getDeptId());
		return this.save(own);
	}

	/**
	 * 更新关系
	 * @param relation
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateDeptRelation(SysDeptRelation relation) {
		sysDeptRelationMapper.deleteDeptRelations(relation);
		sysDeptRelationMapper.insertDeptRelations(relation);
		return true;
	}

}
